package jumpingnotes.restlet;

import javax.servlet.ServletContext;

import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.Router;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.noelios.restlet.ext.servlet.ServletContextAdapter;

public class JNRestletApplication extends Application {
	private ServletContext servletContext;

	public JNRestletApplication() {
		super();
	}

	public JNRestletApplication(Context context) {
		super(context);
		if (context instanceof ServletContextAdapter) {
			ServletContextAdapter servletContextAdapter = 
				(ServletContextAdapter) context;
			this.servletContext = servletContextAdapter.getServletContext();
		}
	}

	@Override
	public Restlet createRoot() {
		Router root = null;
		if (servletContext != null) {
			WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
			root = (Router) ctx.getBean("restlet.root");
		} else {
			root = new Router(getContext());
			root.attach("/books/{book}", RestletBook.class);
		}
		return root;
	}

}
